<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        placeholder="用户名"
        style="width: 200px;"
        class="filter-item"
        clearable
      />
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" class="filter-item" @click="handleFilter">
        搜索
      </el-button>
      <el-button type="primary" @click="handleCreate">
        添加用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading..."
      border
      fit
      highlight-current-row
    >
      <!-- ID列 -->
      <el-table-column align="center" label="ID" width="80">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
       <!-- 头像列 -->
      <el-table-column label="头像" align="center">
        <template #default="scope">
          <el-avatar :src="getAvatarUrl(scope.row.avatar)" />
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="手机号"  align="center">
        <template #default="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <!-- {{ scope.row.status }} -->
          <el-tag :type="scope.row.status === '1'? 'success' : 'danger'" effect="dark">
            {{ scope.row.status === '1' ? '正常' : '已冻结' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <el-button
            size="small"
            :type="scope.row.status === '1' ? 'warning' : 'success'"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === '1' ? '冻结' : '解锁' }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加用户' : '编辑用户'"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus === 'create'">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
  
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            accept="image/jpeg,image/png,image/gif"
            :on-change="handleAvatarChange">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar-preview" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="avatar-tip">点击上传头像，JPG/PNG/GIF格式</div>
        </el-form-item>
        <el-form-item label="状态">
          <div style="display: flex; align-items: center;">
            <el-tag :type="userForm.status === '1' ? 'success' : 'danger'" effect="dark" style="margin-right: 10px;">
              {{ userForm.status === '1' ? '正常' : '已冻结' }}
            </el-tag>
            <el-radio-group v-model="userForm.status">
              <el-radio label="1">正常</el-radio>
              <el-radio label="0">冻结</el-radio>
            </el-radio-group>
          </div>
          <div class="status-tip" style="margin-top: 5px; font-size: 12px; color: #909399;">
            <span style="color: #67c23a">正常：</span>用户可以正常登录并使用系统
            <br>
            <span style="color: #f56c6c">冻结：</span>用户无法登录，账号被临时禁用
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '../../utils/api'
import { Plus } from '@element-plus/icons-vue'

// API基础URL - 用于拼接头像完整URL
const API_BASE_URL = 'http://localhost:3000'

// 用户数据列表
const list = ref([])  //存储用户列表数据
const total = ref(0)
const listLoading = ref(true)
const dialogFormVisible = ref(false)  //控制表单对话框显示状态
const dialogStatus = ref('')  //表单对话框状态
const userFormRef = ref(null)
const avatarUrl = ref('')
const avatarFile = ref(null)

// 查询参数
const listQuery = reactive({
  page: 1,
  limit: 10,
  username: '',
  status: ''
})

// 表单数据
const userForm = reactive({
  id: undefined,
  username: '',
  password: '',
  phone: '',
  avatar: '',
  status: '1'
})

// 获取头像完整URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' // 默认头像
  
  if (avatar.startsWith('http')) {
    return avatar // 已经是完整URL
  }
  
  return `${API_BASE_URL}/uploads/${avatar}`  //拼接URL
}

// 处理头像变更
const handleAvatarChange = (file) => {
  avatarFile.value = file.raw
  avatarUrl.value = URL.createObjectURL(file.raw)  //生成本地预览URL
}

// 表单验证规则
const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

// 获取用户列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const result = await userAPI.getList(listQuery)
    console.log(result);
    
    list.value = result.data.list
    total.value = result.data.total
  } catch (error) {
    console.error('获取用户列表错误:', error)
    // 错误处理已在请求拦截器中完成
  } finally {
    listLoading.value = false
  }
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  listQuery.limit = val
  getList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  listQuery.page = val
  getList()
}

// 处理搜索过滤
const handleFilter = () => {
  listQuery.page = 1  //重置到第一页
  getList()
}

// 处理添加用户
const handleCreate = () => {
  resetForm()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
}



// 处理删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该用户吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await userAPI.delete(row.id)
        ElMessage.success('删除成功')
        getList() // 重新获取列表
      } catch (error) {
        console.error('删除用户错误:', error)
        // 错误处理已在请求拦截器中完成
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理状态变更
const handleStatusChange = async (row) => {
  // 根据当前状态确定操作类型
  const isFreeze = row.status === '1';
  const actionText = isFreeze ? '冻结' : '解锁';
  const newStatus = isFreeze ? '0' : '1';
  
  // 显示确认对话框
  ElMessageBox.confirm(
    `确定要${actionText}用户 "${row.username}" 的账号吗？`, 
    `${actionText}确认`, 
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: isFreeze ? 'warning' : 'success'
    }
  ).then(async () => {
    try {
      // 调用API更新状态
      await userAPI.updateStatus({
        id: row.id,
        status: newStatus
      });
      
      // 更新本地数据
      row.status = newStatus;
      
      ElMessage.success(`已成功${actionText}用户 "${row.username}" 的账号`);
    } catch (error) {
      console.error(`${actionText}账号失败:`, error);
      ElMessage.error(`${actionText}账号失败，请重试`);
    }
  }).catch(() => {
    // 用户取消操作，不做任何更改
  });
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogStatus.value === 'create') {
          // 创建新用户，这里应该调用注册API
          const formData = new FormData()
          formData.append('username', userForm.username)
          formData.append('password', userForm.password)
          formData.append('phone', userForm.phone)
          
          // 如果选择了头像文件
          if (avatarFile.value) {
            formData.append('head_img', avatarFile.value)
          }
          
          // 使用原生fetch上传文件
          const response = await fetch('http://localhost:3000/register', {
            method: 'POST',
            body: formData
          })
          
          const result = await response.json()
          
          if (result.code === 200) {
            ElMessage.success('添加成功')
            dialogFormVisible.value = false
            getList() // 重新获取列表
          } else {
            ElMessage.error(result.message || '添加失败')
          }
        } else {
          // 更新现有用户
          if (avatarFile.value) {
            // 如果更新了头像，需要使用FormData
            const formData = new FormData()
            formData.append('id', userForm.id)
            formData.append('username', userForm.username)
            formData.append('phone', userForm.phone)
            formData.append('head_img', avatarFile.value)
            formData.append('status', userForm.status)
            
            // 使用fetch上传
            const response = await fetch(`${API_BASE_URL}/admin/users`, {
              method: 'PUT',
              body: formData,
              headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              }
            })
            
            const result = await response.json()
            
            if (result.code === 200) {
              ElMessage.success('更新成功')
              dialogFormVisible.value = false
              getList() // 重新获取列表
            } else {
              ElMessage.error(result.message || '更新失败')
            }
          } else {
            // 没有更新头像，使用普通API
            await userAPI.update({
              id: userForm.id,
              username: userForm.username,
              phone: userForm.phone,
              status: userForm.status
            })
            
            ElMessage.success('更新成功')
            dialogFormVisible.value = false
            getList() // 重新获取列表
          }
        }
      } catch (error) {
        console.error('提交表单错误:', error)
        // 错误处理已在请求拦截器中完成
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  
  Object.keys(userForm).forEach(key => {
    if (key === 'status') {
      userForm[key] = '1'
    } else {
      userForm[key] = ''
    }
  })
  
  // 清除头像预览和文件
  avatarUrl.value = ''
  avatarFile.value = null
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-container {
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex-shrink: 0;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  padding: 10px;
  text-align: right;
  background-color: #fff;
  flex-shrink: 0;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

.status-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.5;
}
</style> 